<template>
	<div class="chat-window" v-if="selectedChat">
		<div class="chat-header">{{ selectedChat.name }}</div>
		<div class="chat-messages" ref="chatbox">
			<div v-for="message in selectedChat.messages" :key="message.id" class="message">
				<div v-if="message.type === 'received'" class="received">
					<img :src="selectedChat.avatar" alt="Avatar" class="avatar" />
					<div class="message-content">{{ message.content }}</div>
				</div>
				<div v-else class="sent">
					<div class="message-content">{{ message.content }}</div>
					<img :src="currentUserAvatar" alt="Avatar" class="avatar" />
				</div>
			</div>
		</div>
		<div class="chat-input">
			<input type="text" v-model="newMessage" id="msgInput" placeholder="给对方的信息..." />
			<button @click="sendMessage">发送</button>
		</div>
	</div>
</template>

<script>
	import {
		getSocket
	} from 'utils/socketUtils.js';
	//socket实例
	import {
		socketInstance
	} from "utils/socketUtils.js"




	export default {
		data() {
			return {
				selectedChat: {

				},
				newMessage: '',
				currentUserAvatar: ''
			}
		},

		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			this.selectedChat = JSON.parse(decodeURIComponent(option.selectedChat));
			console.log(this.selectedChat, "this.selectedChat");
			this.getChatList(this.selectedChat);


		},
		onShow() {

		},
		onBackPress(e) {
			console.log(this.selectedChat.id, '返回了')
			this.$globalData.extraParam = this.selectedChat.id;

		},
		mounted() {
			this.currentUserAvatar = "http://localhost:8080" + uni.getStorageSync('userInfo').avatar || ';'
			//连接socket
			socketInstance(uni.getStorageSync('Token'), uni.getStorageSync('username'));
			const scocket = getSocket();
			scocket.on('connect', () => { // 默认通道 connect是通道名称
				console.log('连接成功');
			});
			scocket.on('channel_user', (data) => { // 自定义通道 前后端约定
				console.log('chat页面，监听到channel_user消息：', data);
				const msgData = JSON.parse(data);
				//监听到当前窗口的用户发来的消息
				if (msgData.senderId === this.selectedChat.id) {
					this.selectedChat.messages.push({
						id: Date.now(),
						type: 'received',
						content: msgData.msgContent,
					});
				}
				//让滚动条滚到最下面
				this.$nextTick(() => {
					this.$refs.chatbox.scrollTop = this.$refs.chatbox.scrollHeight;
				});
				//读取完消息后得标记完已读，不然列表会继续显示未读
				//设置该用户聊天信息为已读
				uni.request({
					url: '/dev-api/system/sendMsg/updateMsgRead',
					method: "post",
					data: {
						receiverIds: uni.getStorageSync('userInfo').userId + "",
						senderId: this.selectedChat.id
					},
					header: {
						'Authorization': 'Bearer ' + uni.getStorageSync('Token'),
						'Content-Type': 'application/json;charset=utf-8'
					},
					success: res => {
						console.log(res, "消息标记为已读")
					}
				})

			});
			scocket.on('channel_system', (data) => { // 自定义通道
				console.log('监听到系统channel_system消息：');
				console.log(data);
			});
			scocket.on('disconnect', () => { // 默认通道
				console.log('断开连接');
			});

			document.getElementById('msgInput').addEventListener('keydown', event => {
			    if (event.key === 'Enter') {
					this.sendMessage();
			    }
			});
			
		},
		methods: {

			sendMessage() {
				if (this.newMessage.trim() !== '') {
					this.selectedChat.messages.push({
						id: Date.now(),
						type: 'sent',
						content: this.newMessage,
					});
					const token = uni.getStorageSync('Token');
					//消息发送者
					const msgObj = {
						sender: uni.getStorageSync('username'),
						senderId: uni.getStorageSync('userInfo').userId,
						msgContent: this.newMessage,
						receiverId: this.selectedChat.id
					};

					uni.request({
						// 接口地址
						url: '/dev-api/system/sendMsg/sendToOne',
						method: "post",
						data: {
							userId: this.selectedChat.name,
							message: JSON.stringify(msgObj),
						},
						header: {
							'Authorization': 'Bearer ' + token,
							'Content-Type': 'application/json;charset=utf-8'
						},
						success: res => {
							console.log(res)
						}
					});
					this.newMessage = '';
					//设置滚动条在最下面
					this.$nextTick(() => {
						this.$refs.chatbox.scrollTop = this.$refs.chatbox.scrollHeight;
					});
				}
			},
			getChatList(chat) {
				//查询当前聊天窗口的聊天记录
				uni.request({
					url: '/dev-api/system/sendMsg/listBychatId',
					method: "post",
					data: {
						receiverIds: uni.getStorageSync('userInfo').userId + "",
						senderId: chat.id
					},
					header: {
						'Authorization': 'Bearer ' + uni.getStorageSync('Token'),
						'Content-Type': 'application/json;charset=utf-8'
					},
					success: res => {
						console.log(res.data, "聊天记录")
						const chatArr = res.data || [];
						chatArr.forEach(chatItem => {
							this.selectedChat.messages.push({
								id: chatItem.msgId,
								type: chatItem.senderId == chat.id ? 'received' : 'sent',
								content: chatItem.messageContent,
							})
						})
						//让滚动条滚到最下面
						this.$nextTick(() => {
							this.$refs.chatbox.scrollTop = this.$refs.chatbox.scrollHeight;
						});
					}
				})
			}
		}
	}
</script>

<style scoped>
	.chat-window {
		display: flex;
		flex-direction: column;
		height: 95vh;
	}

	.chat-header {
		background-color: #f0f0f0;
		padding: 10px;
		text-align: center;
	}

	.chat-messages {
		flex: 1;
		/* overflow-y: auto; */
		overflow-y: scroll;
		padding: 10px;
	}

	.message {
		display: flex;
		margin-bottom: 10px;
	}

	.received {
		display: flex;
		align-items: center;
	}

	.sent {
		display: flex;

		/* justify-content: flex-end; */
		margin-left: auto;
		/* margin-left:auto 靠右对齐 */
		align-items: center;
	}

	.avatar {
		width: 30px;
		height: 30px;
		border-radius: 50%;
		margin-right: 10px;
	}

	.message-content {
		padding: 10px;
		border-radius: 10px;
	}

	.received .message-content {
		background-color: #e0e0e0;
	}

	.sent .message-content {
		background-color: #007bff;
		color: white;
	}

	.chat-input {
		display: flex;
		align-items: center;
		padding: 10px;
		margin-top: auto;
	}

	.chat-input input {
		flex: 1;
		padding: 10px;
		border: 1px solid #ccc;
		border-radius: 5px;
		margin-right: 10px;
	}

	.chat-input button {
		padding: 10px 20px;
		border: none;
		border-radius: 5px;
		background-color: #007bff;
		color: white;
		cursor: pointer;
	}
</style>